<template>
  <div class="bigbox">
    <div class="leftbox">
      <div class="l-top">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="openAdd"
          >新 增</el-button
        >
        <el-button
          type="primary"
          size="small"
          icon="el-icon-edit"
          @click="openEdit"
          >编 辑</el-button
        >
        <el-button type="danger" size="small" icon="el-icon-delete" @click="del"
          >删 除</el-button
        >
      </div>
      <div class="l-b">
        <el-tree
          ref="tree"
          :data="treeList"
          :props="defaultProps"
          @node-click="handleNodeClick"
          :current-node-key="checkedId"
          node-key="id"
          highlight-current
        ></el-tree>
        <el-dialog
          :title="title"
          :visible.sync="addVisible"
          width="20%"
          :before-close="handleClose"
        >
          <el-input v-model="appName"></el-input>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="add">确 定</el-button>
            <el-button @click="handleClose">取 消</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
    <div class="rightbox">
      <TopTitle :showexcel="false" @command="command" @shuaxin="shuaxin">
        <template v-slot:leftother>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-upload2"
            @click="openUpload"
            >上 传</el-button
          >
        </template>
      </TopTitle>
      <nt-table
        :issize="issize"
        max-height="100%"
        :fit="true"
        :tableData="apkList"
        :tableConfig="tableConfig"
        v-loading="loading"
      >
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <div class="options">
              <el-tooltip content="编辑" placement="top"
                ><i
                  style="margin-right: 20px; color: #3f94e4; cursor: pointer"
                  class="el-icon-edit"
                  @click="editUpload(scope.row)"
                ></i>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-popconfirm
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  title="确定要删除吗？"
                  @confirm="delApk(scope.row)"
                >
                  <!-- <template #reference> -->
                  <i
                    slot="reference"
                    class="el-icon-delete"
                    style="margin-right: 20px; color: red; cursor: pointer"
                  ></i>
                  <!-- </template> -->
                </el-popconfirm>
              </el-tooltip>
              <el-popover placement="bottom" trigger="click">
                <div
                  style="
                    width: 100%;
                    height: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  "
                >
                  <vue-qr
                    ref="qrCode"
                    :text="getQrCodeText(scope.row.id)"
                    :logoSrc="dntlogo"
                    width="100"
                    height="100"
                  ></vue-qr>
                </div>
                <template #reference>
                  <el-tooltip content="下载该版本" placement="top">
                    <img
                      style="
                        width: 14px;
                        height: 14px;
                        cursor: pointer;
                        margin-bottom: -1px;
                      "
                      src="@/assets/ewm.svg"
                      mode="scaleToFill" /></el-tooltip></template
              ></el-popover>
            </div>
          </template>
        </el-table-column>
      </nt-table>
      <el-dialog
        :visible.sync="uploadVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-form
          :model="form"
          ref="form"
          :rules="rules"
          label-width="80px"
          :inline="false"
          size="normal"
        >
          <el-form-item label="APP名称" prop="appName">
            <el-input v-model="form.appName" disabled></el-input>
          </el-form-item>
          <el-form-item label="版本号" prop="version">
            <el-input v-model="form.version"></el-input>
          </el-form-item>
          <el-form-item label="更新内容" prop="content">
            <el-input v-model="form.content"></el-input>
          </el-form-item>
          <el-form-item label="应用程序" prop="ossFileName">
            <el-upload
              class="upload-demo"
              action="#"
              :on-change="handleChange"
              :limit="1"
              accept=".apk"
              :on-exceed="handleExceed"
              :auto-upload="false"
              :file-list="fileList"
            >
              <el-button size="small" type="primary" :loading="btnloading"
                >点击上传</el-button
              >
            </el-upload>
          </el-form-item>
          <el-form-item label="更新时间">
            <el-input disabled v-model="form.uploadTime"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="upload" :loading="btnloading"
            >确 定</el-button
          >
          <el-button @click="handleClose">取 消</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  addApkListApi,
  addAppApi,
  delApkListApi,
  delAppApi,
  downLoadApi,
  editApkListApi,
  getApkListApi,
  getAppListApi,
  updateAppApi,
  uploadApkApi
} from '@/api/App-control/App-control'
import dntlogo from '@/assets/dnt.png'
import TopTitle from '@/components/TopTitle/newtitle.vue'
import NtTable from '@/components/nt-table'
import dayjs from 'dayjs'
export default {
  components: { TopTitle, NtTable },
  data() {
    return {
      state: 'add',
      loading: false,
      btnloading: false,
      appName: '',
      title: '应用名称',
      dntlogo: dntlogo,
      form: {},
      treeList: [],
      apkList: [],
      fileList: [],
      rules: {
        appName: [
          { required: true, message: '请输入APP名称', trigger: 'blur' }
        ],
        version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
        ossFileName: [
          { required: true, message: '请上传apk文件', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入更新内容', trigger: 'blur' }
        ]
      },
      addVisible: false,
      uploadVisible: false,
      defaultProps: {
        label: 'appName'
      },
      checkedId: '',
      issize: 'medium',
      tableConfig: [
        {
          label: '序号',
          type: 'index',
          width: '100px',
          align: 'center'
        },
        {
          label: 'APP名称',
          prop: 'appName'
        },
        {
          label: '版本号',
          prop: 'version'
        },
        {
          label: '更新内容',
          prop: 'content'
        },
        {
          label: '应用程序',
          prop: 'fileName'
        },
        {
          label: '更新时间',
          prop: 'uploadTime'
        }
      ]
    }
  },
  created() {
    this.getAppList()
  },
  methods: {
    getQrCodeText(apkId) {
      if (typeof window !== 'undefined') {
        console.log(
          `${window.location.origin}/sst-microservice-biz/sst/apk/control/apk/download?apkId=${apkId}`
        )

        return `${window.location.origin}/biz/sst-microservice-biz/sst/apk/control/apk/download?apkId=${apkId}`
      }
      return ''
    },
    async getApkList(id) {
      try {
        this.loading = true
        const res = await getApkListApi({
          appId: id,
          pageNo: 0,
          pageSize: 1000
        })
        this.apkList = res.data.list
      } catch (error) {
      } finally {
        this.loading = false
      }
    },
    async getAppList() {
      const res = await getAppListApi()
      this.treeList = res.data.list
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(res.data.list[0].id)
      })
      this.getApkList(res.data.list[0].id)
    },
    openAdd() {
      this.title = '应用名称'
      this.state = 'add'
      this.addVisible = true
    },
    openEdit() {
      this.title = '编辑应用名称'
      this.state = 'edit'
      this.appName = this.$refs.tree.getCurrentNode()?.appName
      this.addVisible = true
    },
    async add() {
      if (this.state === 'add') {
        try {
          const res = await addAppApi({
            appName: this.appName
          })
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '新增成功',
              duration: 1500
            })
            this.addVisible = false
            this.getAppList()
            this.handleClose()
          } else {
            this.$message({
              type: 'danger',
              message: res.message,
              duration: 1500
            })
          }
        } catch (error) {}
      } else {
        try {
          const res = await updateAppApi({
            appName: this.appName,
            id: this.$refs.tree.getCurrentNode()?.id
          })
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '修改成功',
              duration: 1500
            })
            this.addVisible = false
            this.getAppList()
            this.handleClose()
          } else {
            this.$message({
              type: 'danger',
              message: res.message,
              duration: 1500
            })
          }
        } catch (error) {}
      }
    },
    async del() {
      this.$confirm('请确认是否删除该APP?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await delAppApi(this.$refs.tree.getCurrentKey())
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功',
                duration: 1500
              })
              this.addVisible = false
              this.getAppList()
            } else {
              this.$message({
                type: 'danger',
                message: res.message,
                duration: 1500
              })
            }
          } catch (error) {}
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    openUpload() {
      this.state = 'add'
      this.form.appName = this.$refs.tree.getCurrentNode()?.appName
      this.form.uploadTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      this.uploadVisible = true
    },
    async upload() {
      await this.$refs.form.validate()
      try {
        const res =
          this.state === 'add'
            ? await addApkListApi({
                ...this.form,
                appId: this.$refs.tree.getCurrentKey()
              })
            : await editApkListApi({
                ...this.form
              })
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: this.state === 'add' ? '新增成功' : '修改成功',
            duration: 1500
          })
          this.handleClose()
          this.getApkList(this.$refs.tree.getCurrentKey())
        } else {
          this.$message({
            type: 'danger',
            message: res.message,
            duration: 1500
          })
        }
      } catch (error) {}
    },
    command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },
    // 处理文件上传改变事件
    async handleChange(file, fileList) {
      console.log('上传的文件：', file)
      console.log('文件列表：', fileList)
      try {
        this.btnloading = true
        const res = await uploadApkApi({
          id: this.$refs.tree.getCurrentKey(),
          uploadFile: file.raw
        })
        console.log(res)

        if (res.code == 200) {
          this.form.ossFileName = res.data.entity
          this.form.fileName = file.name
        } else {
          this.$message({
            type: 'info',
            message: res.message | '上传失败'
          })
        }
      } catch (error) {
      } finally {
        this.btnloading = false
      }
    },
    editUpload(row) {
      this.state = 'edit'
      this.form = { ...row }
      this.fileList = [{ name: row.fileName }]
      this.uploadVisible = true
      console.log(row)
    },
    async delApk(row) {
      try {
        // 调用删除 APK 列表的 API
        const res = await delApkListApi(row.id)
        if (res.code === 200) {
          // 若删除成功，显示成功提示信息
          this.$message({
            type: 'success',
            message: '删除成功',
            duration: 1500
          })
          // 重新获取当前应用下的 APK 列表，以更新界面
          this.getApkList(this.$refs.tree.getCurrentKey())
        } else {
          // 若删除失败，显示错误提示信息
          this.$message({
            type: 'danger',
            message: res.message,
            duration: 1500
          })
        }
      } catch (error) {}
    },
    //下载某版本
    async downLoad(row) {
      const res = await downLoadApi(row.id)
    },
    // 超出文件数量限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(`只能上传1个文件`)
    },
    shuaxin() {
      this.getApkList(this.$refs.tree.getCurrentKey())
    },
    handleNodeClick(data) {
      console.log(data)
      this.getApkList(data.id)
    },
    handleClose() {
      this.addVisible = false
      this.uploadVisible = false
      this.appName = ''
      this.form = {}
      this.fileList = []
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
}
.options {
  display: flex;
  align-items: center;
  justify-content: center;
}
.bigbox {
  display: flex;
  height: 100%;
  padding: 10px;
  .leftbox {
    padding: 20px;
    width: 300px;
    height: 100%;
    background-color: #fff;
    margin-right: 10px;
    .l-top {
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin-bottom: 20px;
    }
  }
  .rightbox {
    flex: 1;
    width: 0;
    display: flex;
    flex-direction: column;
    height: 100%;
    background-color: #fff;
    padding: 20px;
  }
}
</style>
